package com.uziot.bucket.security.config.filter;

import com.uziot.bucket.security.config.LoginUser;
import com.uziot.bucket.security.util.SecurityUtils;
import com.uziot.bucket.security.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

/**
 * @author shidt
 * @version V1.0
 * @className AuthenticationTokenFilter
 * @date 2020-12-04 11:25:02
 * @description token过滤器 验证token有效性
 */

@Component
@SuppressWarnings("All")
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsServiceImpl;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String username = request.getHeader("username");
        LoginUser loginUser = (LoginUser) userDetailsServiceImpl.loadUserByUsername(username);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            // 如果用户信息校验正常，则判断是否要续期，需要则执行续时操作
            // tokenService.refreshTokenIfNeed(loginUser);
            // 注入认证和授权信息
            Collection<? extends GrantedAuthority> authorities = loginUser.getAuthorities();
            UsernamePasswordAuthenticationToken authenticationToken
                    = new UsernamePasswordAuthenticationToken(loginUser, null, authorities);
            WebAuthenticationDetails webAuthenticationDetails = new WebAuthenticationDetailsSource().buildDetails(request);
            authenticationToken.setDetails(webAuthenticationDetails);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
